(function() {
  var $email_regex, $form_valid, $school_nz_regex, set_valid, validate_email, validate_password;

  $form_valid = [false, false, false, false, false];

  $email_regex = /\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;

  $school_nz_regex = /\.school\.nz$/;

  set_valid = function(id, valid) {
    console.log("Valid: " + valid);
    if (valid) {
      $("#" + id + "-wrapper").removeClass('error');
      return $("#" + id + "-error").fadeIn();
    } else {
      $("#" + id + "-wrapper").removeClass('error');
      return $("#" + id + "-error").hide();
    }
  };

  validate_email = function(text) {
    return $email_regex.test(text) && $school_nz_regex.test(text);
  };

  validate_password = function(text) {
    return text.length >= 8;
  };

  $(function() {
    $('#username-box').change(function() {
      return set_valid('username', $('#username-box').val() !== "");
    });
    $('#id-box').change(function() {
      if ($('#id-box').val().length !== 3) {
        set_valid('id', false);
        return;
      }
      return $.post('/school/id/check', {
        i: $('#id-box').val()
      }, function(data) {
        return set_valid('id', data.error != null);
      });
    });
    $('#email-box').change(function() {
      return set_valid('email', validate_email($('#email-box').val()));
    });
    $('#password-box').change(function() {
      return set_valid('password', validate_password($('#password-box').val()));
    });
    $('#password-confirm').change(function() {
      return set_valid('confirm', $('#password-confirm').val() === $('#password-box').val());
    });
    return $('#submit-btn').click(function() {
      var params;
      if (_.contains($form_valid, false)) {
        $.meow({
          message: "You can't sign up until you've completed the form."
        });
      }
      params = {
        u: $('#username-box').val(),
        i: $('#id-box').val(),
        e: $('#email-box').val(),
        p: hash($('#password-box').val())
      };
      return $.post('/signup/school/validate', params, function(data) {
        if (data.error != null) {
          return $.meow({
            message: "The server doesn't like your values ... Check the form is valid, and if it is then <a href='/contact'>contact us!</a>"
          });
        } else {
          $('#main').fadeOut();
          return $('#validate').fadeIn();
        }
      });
    });
  });

}).call(this);
